package com.yeyks.controller.order;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.annotation.NeedToken;
import com.yeyks.annotation.SystemLog;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.base.PageResult;
import com.yeyks.common.constants.AccountType;
import com.yeyks.common.constants.SysLogMsg;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.param.OrderDownParam;
import com.yeyks.common.param.OrderListParam;
import com.yeyks.common.result.OrderDownloadResult;
import com.yeyks.common.result.OrderHeadDetail;
import com.yeyks.common.result.OrderListResult;
import com.yeyks.common.utils.DateUtils;
import com.yeyks.common.utils.IdWorkerUtil;
import com.yeyks.common.utils.ObjectConvertUtil;
import com.yeyks.common.utils.excel.ExcelUtil;
import com.yeyks.commonReference.service.order.OrderBillService;
import com.yeyks.commonReference.service.order.OrderHeadService;
import com.yeyks.order.dal.domain.OrderBill;
import com.yeyks.order.dal.domain.OrderHead;
import com.yeyks.web.AccountUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * @author fuchangshuai
 * @since 2019-07-03
 */
@Api(tags = "新订单模块")
@RestController
@Slf4j
@RequestMapping(value = "/orderHead")
public class OrderHeadController {
    @Autowired
    private OrderHeadService orderHeadService;

    @Autowired
    private OrderBillService orderBillService;

    /**
     * web订单退款
     *
     * @param orderNo
     * @return
     */
    @SystemLog(value = SysLogMsg.ORDER_REFUND)
    @NeedToken
    @RequestMapping(value = "/refund/web", method = RequestMethod.POST)
    @ApiOperation(value = "web订单退款", notes = "token通过headler传入")
    @ApiImplicitParam(paramType = "query", name = "orderNo", value = "订单号", required = true, dataType = "String")
    public AjaxResponseBody refundWeb(@RequestParam(name = "orderNo") String orderNo) {
        orderHeadService.refundWeb(AccountUtils.getLoginUser(), orderNo);
        return AjaxResponseBody.success();
    }

    /**
     * 分页获取订单
     *
     * @param param
     * @return
     */
    @NeedToken
    @ApiOperation(value = "订单分页查询列表", notes = "根据不同的角色实现订单列表查询", response = OrderListResult.class)
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public AjaxResponseBody<PageResult<OrderListResult>> list(@Validated OrderListParam param) {
        AccountInfo loginUser = AccountUtils.getLoginUser();
        List<Integer> typeLists = Lists.newArrayList(1, 2, 3, 4, 5, 10, 11, 12, 20, 21, 22);
        Arguments.isTrue(!typeLists.contains(loginUser.getType()), "您无权查看");
        PageResult<OrderListResult> pageResult = orderHeadService.myList(loginUser, param);
        return AjaxResponseBody.success(pageResult);
    }

    /**
     * 导出订单
     *
     * @param response
     * @return
     */
    @NeedToken
    @CrossOrigin
    @ApiOperation(value = "导出订单", notes = "导出订单")
    @PostMapping(value = "/downOrder")
    public void downOrder(@Validated OrderDownParam param, HttpServletResponse response) {
        param.setSourceType("yyks");
        List<OrderDownloadResult> orderDownloadResults = orderHeadService.selectDownloadOrder(AccountUtils.getLoginUser(), param);
        ExcelUtil.disposeWriteExcelWithSheets(response, orderDownloadResults, new OrderDownloadResult());
    }

    @NeedToken
    @ApiOperation(value = "导出CN订单", notes = "导出CN订单")
    @PostMapping(value = "/downCNOrder")
    public void downCNOrder(@Validated OrderDownParam param, HttpServletResponse response) {
        param.setSourceType("cn");
        List<OrderDownloadResult> orderDownloadResults = orderHeadService.selectDownloadOrder(AccountUtils.getLoginUser(), param);
        ExcelUtil.disposeWriteExcelWithSheets(response, orderDownloadResults, new OrderDownloadResult());
    }

    /**
     * 修改订单状态
     *
     * @return
     */
    @SystemLog(value = SysLogMsg.ORDER_UPDATE_STATUS)
    @NeedToken
    @ApiOperation(value = "修改订单状态", notes = "修改订单状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orderNo", value = "订单号", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "订单状态(1待支付，2待入住，3已完成，4支付失败，5待退款，6已退款，7入住中，8已取消，9已评论)", dataType = "int")
    })
    @PostMapping(value = "/update/status")
    public AjaxResponseBody updateStatus(@RequestParam(name = "orderNo") String orderNo,
                                         @RequestParam(name = "status") Integer status) {
        AccountInfo accountInfo = AccountUtils.getLoginUser();
        if (accountInfo.getType() != AccountType.HotelManager
                && AccountType.Administrator != accountInfo.getType()) {
            throw new ServiceException("您无权操作");
        }
        orderHeadService.updateStatusByOrderNo(orderNo, status);
        return AjaxResponseBody.success();
    }

    /**
     * 订单详情
     *
     * @return
     */
    @ApiOperation(value = "订单详情", notes = "订单详情", response = OrderHeadDetail.class)
    @ApiImplicitParam(paramType = "query", name = "orderNo", value = "订单号", dataType = "String")
    @PostMapping(value = "/detail")
    public AjaxResponseBody<OrderHeadDetail> detail(@RequestParam(name = "orderNo") String orderNo) {
        if (Arguments.strIsNull(orderNo)) {
            throw new ServiceException("订单号不能为空");
        }
        OrderHeadDetail detail = orderHeadService.getOrderDetail(orderNo);
        return AjaxResponseBody.success(detail);
    }

    @ApiOperation(value = "测试下单接口", notes = "测试下单接口")
    @PostMapping(value = "/test/insert")
    public AjaxResponseBody<Object> insertTest(@RequestParam(value = "count", defaultValue = "1") Integer count,
                                               @RequestParam(value = "inTime") String inTime,
                                               @RequestParam(value = "outTime") String outTime,
                                               @RequestParam(value = "userId") Integer userId){

        List<ContactUser> contactUsers = Lists.newArrayList(
                new ContactUser("史云熠","15157231384"),
                new ContactUser("曹雪娇","18257275165"),
                new ContactUser("戴园园","15157230948"),
                new ContactUser("王姗姗","15857237222"),
                new ContactUser("赵峰","18868207078"),
                new ContactUser("施思","18767222610"),
                new ContactUser("姚诚诚","18657205250"),
                new ContactUser("奚梦","13718519466"),
                new ContactUser("刘云婷","15165093305"),
                new ContactUser("李小吉","13587254661"),
                new ContactUser("朱莎莎","18767290758"),

                new ContactUser("吕东升","15157231384"),
                new ContactUser("王房名","18257275165"),
                new ContactUser("丁戴","15157230948"),
                new ContactUser("王先君","15857237222"),
                new ContactUser("赵易峰","18868207078"),
                new ContactUser("施程思","18767222610"),
                new ContactUser("姚小程","18657205250"),
                new ContactUser("奚露露","13718519466"),
                new ContactUser("刘子家","15165093305"),
                new ContactUser("李程","13587254661"),
                new ContactUser("王莎莎","18767290758"),

                new ContactUser("刘梦","15157231384"),
                new ContactUser("王小雨","18257275165"),
                new ContactUser("丁魏","15157230948"),
                new ContactUser("王家臣","15857237222"),
                new ContactUser("赵启程","18868207078"),
                new ContactUser("施嘉伟","18767222610"),
                new ContactUser("姚大卫","18657205250"),
                new ContactUser("奚家琪","13718519466"),
                new ContactUser("刘梦依","15165093305"),
                new ContactUser("李小路","13587254661"),
                new ContactUser("王珊珊","18767290758"),

                new ContactUser("刘达","15157231384"),
                new ContactUser("王齐预","18257275165"),
                new ContactUser("丁昕然","15157230948"),
                new ContactUser("王霞","15857237222"),
                new ContactUser("赵沙沙","18868207078"),
                new ContactUser("施棋路","18767222610"),
                new ContactUser("姚模棋","18657205250"),
                new ContactUser("奚道生","13718519466"),
                new ContactUser("刘佳佳","15165093305"),
                new ContactUser("李雨桐","13587254661"),
                new ContactUser("王名","18767290758"),

                new ContactUser("史晓波","19857241066")

        );

        AjaxResponseBody<Object> body = AjaxResponseBody.failed();

        int contactCount = contactUsers.size();
        int cou = orderHeadService.count( new QueryWrapper<OrderHead>( ).eq( OrderHead.SOURCE_TYPE, "cn" ) );

        List<OrderHead> orderHeadList = Lists.newArrayList();
        List<OrderBill> orderBillList = Lists.newArrayList();
        if(count > 0){
            for(int i=0; i < count; i ++){
               OrderHead orderHead = orderHeadService.getOne( new QueryWrapper<OrderHead>( )        
                    .eq( OrderHead.SOURCE_TYPE, "cn" ).last( "limit " + RandomUtil.randomInt( cou ) + ",1" ) );
               OrderBill orderBill = orderBillService.getOne( new QueryWrapper<OrderBill>()
                    .eq( OrderBill.ORDER_NO, orderHead.getOrderNo()).last( "limit 1" ) );
               int index = RandomUtil.randomInt( contactCount );
               ContactUser contactUser = contactUsers.get( index );
               OrderHead insertOrder = new OrderHead();
               OrderBill orderBills = new OrderBill();
               String orderNo = "cnc2b" + IdWorkerUtil.nextStrId();
               insertOrder = ObjectConvertUtil.convertObject( orderHead, OrderHead.class);
               insertOrder.setOrderNo( orderNo);
               insertOrder.setCheckIn( DateUtils.yyyyMMddToDate( inTime ) );
               insertOrder.setCheckOut( DateUtils.yyyyMMddToDate( outTime ) );
               insertOrder.setGmtCreate( DateUtils.yyyyMMddToDate( inTime ) );
               insertOrder.setGmtModified( DateUtils.yyyyMMddToDate( inTime ) );
               insertOrder.setUserId( userId );
               insertOrder.setStatus( 3 );
               insertOrder.setContactName( contactUser.getContactName() );
               insertOrder.setContactPhone( contactUser.getPhone() );
               insertOrder.setLeaveMessage( "yyks_cn_insert" );
               insertOrder.setPaymentMethod( RandomUtil.randomInt( 2 ) );

               if(null != orderBill){
                   orderBills = ObjectConvertUtil.convertObject( orderBill, OrderBill.class );
                   orderBills.setOrderNo( orderNo );
                   orderBills.setInDate( DateUtils.yyyyMMddToDate( inTime ) );
                   orderBillList.add(orderBills);
               }
                orderHeadList.add(insertOrder);
            }
            boolean b = orderHeadService.saveBatch( orderHeadList );
            orderBillService.saveBatch(orderBillList);
            if(b){
                body = AjaxResponseBody.success("导入信息成功");
            }
        }
        return body;
    }
}

@Data
@AllArgsConstructor
class ContactUser{
    private String contactName;
    private String phone;
}